var express = require('express');
var router = express.Router();
var { conn, isError, dateFormat, isLogin } = require("../untils");
var { ObjectID } = require("mongodb");
var { waterfall } = require("async");

router.get('/submit', function (req, res) {
    var session_username = req.session.username;
    var content_edit = req.cookies.content_edit;
    var db_name = req.query.db_name;
    var _id = req.query._id;
    isLogin(session_username, res, () => {
        conn((err, db) => {
            isError(err, res, db);
            var news_edit_info = db.collection("news_edit_info");
            var insert_time = dateFormat(new Date(), "yyyy年mm月dd日 hh时SS分ss秒");
            var news_id = ObjectID(_id);
            waterfall([
                (callback) => {
                    news_edit_info.find({ status: 1, news_id, edit_name: session_username }, {}).toArray((err, result) => {
                        if (err) {
                            callback(err, null);
                        } else {
                            if (result.length !== 0) {
                                callback(null, true);
                            } else {
                                callback(null, false);
                            }
                        }
                    });
                },
                (args, callback) => {
                    if (!args) {
                        news_edit_info.insert({ status: 1, news_id, content_edit, edit_name: session_username, insert_time }, (err, result) => {
                            if (err) {
                                callback(err, null);
                            } else {
                                callback(null, result);
                            }
                        })
                    } else {
                        news_edit_info.update({ status: 1, news_id, edit_name: session_username }, { $set: { content_edit, insert_time } }, (err, result) => {
                            if (err) {
                                callback(err, null);
                            } else {
                                callback(null, result);
                            }
                        });
                    }
                }
            ], (err, result) => {
                isError(err, res, db);
                res.cookie("content_edit", "", { maxAge: 1 });
                res.redirect(`/details?db_name=${db_name}&_id=${_id}`);
                db.close();
            });
        });
    });
});


module.exports = router;